// 让mock拦截前端发送的请求
import Mock from '../plugins/mockjs/mock.js'
import demoApi from './demo.js'

const mocks = [{
	intercept: true,
	fetchs: demoApi
}]

export function param2Obj(url) {
	const search = url.split('?')[1]
	if (!search) {
		return {}
	}
	return JSON.parse(
		'{"' +
		decodeURIComponent(search)
		.replace(/"/g, '\\"')
		.replace(/&/g, '","')
		.replace(/=/g, '":"')
		.replace(/\+/g, ' ') +
		'"}'
	)
}

export function mockXHR() {
	Mock.XHR.prototype.proxy_send = Mock.XHR.prototype.send
	Mock.XHR.prototype.send = function() {
		if (this.custom.xhr) {
			this.custom.xhr.withCredentials = this.withCredentials || false
			if (this.responseType) {
				this.custom.xhr.responseType = this.responseType
			}
		}
		this.proxy_send(...arguments)
	}

	function XHR2ExpressReqWrap(respond) {
		return function(options) {
			let result = null
			if (respond instanceof Function) {
				const {
					body,
					type,
					url
				} = options
				result = respond({
					method: type,
					body: body,
					query: param2Obj(url)
				})
			} else {
				result = respond
			}
			return Mock.mock(result)
		}
	}
	for (const i of mocks) {
		if (i.intercept) {
			for (const fetch of i.fetchs) {
				Mock.mock(new RegExp(fetch.url), fetch.type || 'get', XHR2ExpressReqWrap(fetch.response))
			}
		}
	}

}